package com.sinopec.uhf.uhfhelp

import com.payne.reader.Reader
import com.payne.reader.bean.config.AntennaCount
import com.payne.reader.bean.receive.Failure
import com.payne.reader.bean.receive.Success
import com.payne.reader.bean.send.*
import com.sinopec.uhf.model.ReaderHelper
import kotlinx.coroutines.suspendCancellableCoroutine
import kotlin.coroutines.resume

//ReaderHelper.getReader()
data class SuccessOrFailure(
    val isSuccess: Boolean,
    var success: Success? = null,
    var failure: Failure? = null
)

/**
 * lwj at 2023/5/25
 * 读取功率
 */
internal suspend fun readPower(
    reader: Reader = ReaderHelper.getReader(),
): Int {
    return suspendCancellableCoroutine {
        reader.getOutputPower({ power ->
            it.resume(power?.outputPower?.getOrNull(0)?.toInt() ?: -1)
        }, { failure ->
            it.resume(-1)
        })
    }
}

/**
 * lwj at 2023/5/25
 * 设置功率
 */
internal suspend fun setPower8(
    power: Int,
    reader: Reader = ReaderHelper.getReader(),
): SuccessOrFailure {
    val powerByte = power.toByte()
    val antennaCount = reader.antennaCount
    val config = when (antennaCount) {
        AntennaCount.SINGLE_CHANNEL -> OutputPowerConfig.outputPower(
            PowerSingleAntenna
                .Builder()
                .power(powerByte)
                .build()
        )
        AntennaCount.FOUR_CHANNELS -> OutputPowerConfig.outputPower(
            PowerFourAntenna
                .Builder()
                .powers(ByteArray(antennaCount.value) { powerByte })
                .build()
        )
        AntennaCount.SIXTEEN_CHANNELS -> OutputPowerConfig.outputPower(
            PowerSixteenAntenna
                .Builder()
                .powers(ByteArray(antennaCount.value) { powerByte })
                .build()
        )
        AntennaCount.EIGHT_CHANNELS -> OutputPowerConfig.outputPower(
            PowerEightAntenna
                .Builder()
                .powers(ByteArray(antennaCount.value) { powerByte })
                .build()
        )
    }

    return suspendCancellableCoroutine {
        reader.setOutputPower(config, { success ->
            it.resume(SuccessOrFailure(true, success, null))
        }, { failure ->
            it.resume(SuccessOrFailure(false, null, failure))
        })
    }
}